/****************************************************
 * Modified by Fred Engler
 *
 * Modification: Code modified from the gtkhruler widget.
 * Added two position markers, Selection/movement
 * of position markers is done by clicking and dragging.
 * Metric calculation has been modified to correspond to 
 * CB units/Base pairs for the current zoom level of the FPC contig
 * display.  When a position marker is clicked, a vertical line
 * is drawn across the display to make it easy to see how the
 * postion relates to FPC clones.  All modifications are commented
 * with 'fred'.
 ****************************************************/

/* GTK - The GIMP Toolkit
 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

/*
 * Modified by the GTK+ Team and others 1997-1999.  See the AUTHORS
 * file for a list of people on the GTK+ Team.  See the ChangeLog
 * files for a list of changes.  These files are distributed with
 * GTK+ at ftp://ftp.gtk.org/pub/gtk/. 
 */

#include <math.h>
#include <stdio.h>
#include <string.h>
#include "gtkhfpcruler.h"


#define FPC_RULER_HEIGHT          14
#define MINIMUM_INCR          5
#define MAXIMUM_SUBDIVIDE     5
#define MAXIMUM_SCALES        10

#define ROUND(x) ((int) ((x) + 0.5))

#define SCROLLBAR_WIDTH 22   /*fred 3/13/03*/
#define WINDOW_BORDER 3
#define UPPER_BORDER 148 
#define LOWER_BORDER 28

extern int bar_active;  /*fred 6/10/03*/

static void gtk_hfpcruler_class_init    (GtkHFpcRulerClass *klass);
static void gtk_hfpcruler_init          (GtkHFpcRuler      *hfpcruler);
static gint gtk_hfpcruler_motion_notify (GtkWidget      *widget,
				      GdkEventMotion *event);
static gint gtk_hfpcruler_button_press (GtkWidget      *widget,
				        GdkEventButton *event);
static gint gtk_hfpcruler_button_release (GtkWidget      *widget,
				          GdkEventButton *event);
static void gtk_hfpcruler_draw_ticks    (GtkFpcRuler       *fpcruler);
static void gtk_hfpcruler_draw_pos      (GtkFpcRuler       *fpcruler);
static void gtk_hfpcruler_erase_pos (GtkFpcRuler *fpcruler);

extern GtkFpcRuler *fpcruler;

int pos1_first = 1;
int pos2_first = 1;

guint
gtk_hfpcruler_get_type (void)
{
  static guint hfpcruler_type = 0;

  if (!hfpcruler_type)
    {
      static const GtkTypeInfo hfpcruler_info =
      {
	"GtkHFpcRuler",
	sizeof (GtkHFpcRuler),
	sizeof (GtkHFpcRulerClass),
	(GtkClassInitFunc) gtk_hfpcruler_class_init,
	(GtkObjectInitFunc) gtk_hfpcruler_init,
	/* reserved_1 */ NULL,
        /* reserved_2 */ NULL,
        (GtkClassInitFunc) NULL,
      };

      hfpcruler_type = gtk_type_unique (gtk_fpcruler_get_type (), &hfpcruler_info);
    }

  return hfpcruler_type;
}

static void
gtk_hfpcruler_class_init (GtkHFpcRulerClass *klass)
{
  GtkWidgetClass *widget_class;
  GtkFpcRulerClass *fpcruler_class;

  widget_class = (GtkWidgetClass*) klass;
  fpcruler_class = (GtkFpcRulerClass*) klass;

  widget_class->motion_notify_event = gtk_hfpcruler_motion_notify;
  widget_class->button_press_event = gtk_hfpcruler_button_press;   /*fred 2/26/03*/
  widget_class->button_release_event = gtk_hfpcruler_button_release;   /*fred 2/26/03*/
  widget_class->key_press_event = gtk_hfpcruler_button_release;   /*fred 2/26/03*/

  fpcruler_class->draw_ticks = gtk_hfpcruler_draw_ticks;
  fpcruler_class->draw_pos = gtk_hfpcruler_draw_pos;
}

static void
gtk_hfpcruler_init (GtkHFpcRuler *hfpcruler)
{
  GtkWidget *widget;

  widget = GTK_WIDGET (hfpcruler);
  widget->requisition.width = widget->style->xthickness * 2 + 1;
  widget->requisition.height = widget->style->ythickness * 2 + FPC_RULER_HEIGHT;

  gtk_widget_set_events (widget, GDK_EXPOSURE_MASK
			 | GDK_LEAVE_NOTIFY_MASK
			 | GDK_BUTTON_PRESS_MASK
			 | GDK_KEY_PRESS_MASK
			 | GDK_BUTTON_RELEASE_MASK
			 | GDK_POINTER_MOTION_MASK
			 | GDK_BUTTON_MOTION_MASK);
}


GtkWidget*
gtk_hfpcruler_new (void)
{
  return GTK_WIDGET (gtk_type_new (gtk_hfpcruler_get_type ()));
}

static gint
gtk_hfpcruler_motion_notify (GtkWidget      *widget,
			  GdkEventMotion *event)
{
  GtkFpcRuler *fpcruler;
  gint x;

  g_return_val_if_fail (widget != NULL, FALSE);
  g_return_val_if_fail (GTK_IS_HFPC_RULER (widget), FALSE);
  g_return_val_if_fail (event != NULL, FALSE);

  fpcruler = GTK_FPC_RULER (widget);

  if(fpcruler->selected_pos==0)   /*fred 2/26/03*/
    return TRUE;

  if (event->is_hint)
    gdk_window_get_pointer (widget->window, &x, NULL, NULL);
  else
    x = event->x;


  if(fpcruler->selected_pos==1)  /*fred 2/26/03*/
  {
    fpcruler->position1 = fpcruler->lower + 
           ((fpcruler->upper - fpcruler->lower) * x) / widget->allocation.width;
  }
  else if(fpcruler->selected_pos==2)
  fpcruler->position2 = fpcruler->lower + 
           ((fpcruler->upper - fpcruler->lower) * x) / widget->allocation.width;



  /*  Make sure the fpcruler has been allocated already  */
  if (fpcruler->backing_store != NULL)
    gtk_hfpcruler_draw_pos (fpcruler);

  return FALSE;
}



/*fred 2/26/03*/
static gint
gtk_hfpcruler_button_press(GtkWidget      *widget,
			   GdkEventButton *event)
{
  GtkFpcRuler *fpcruler;
  fpcruler = GTK_FPC_RULER (widget);
  if(event->button==3){
    gtk_menu_popup(GTK_MENU (fpcruler->units_popup_menu),NULL,NULL,NULL,NULL,
                   event->button, event->time);
    return TRUE;
  }
  if(abs((int)event->x - fpcruler->xsrc1) < 
     abs((int)event->x - fpcruler->xsrc2))
  {
     fpcruler->selected_pos=1;
     pos1_first = 1;
     pos2_first = 0;
  }
  else
  {
    fpcruler->selected_pos=2;
    pos2_first = 1;
    pos1_first = 0;
  }
  return TRUE;
}

/*fred 2/26/03*/
static gint
gtk_hfpcruler_button_release(GtkWidget      *widget,
			     GdkEventButton *event)
{
   gtk_hfpcruler_erase_pos(GTK_FPC_RULER(widget));
   GTK_FPC_RULER(widget)->selected_pos=0;
   return FALSE;
}
static void
gtk_hfpcruler_draw_ticks (GtkFpcRuler *ruler)
{
  GtkWidget *widget;
  cairo_t *cr;
  gint i;
  gint width, height;
  gint xthickness;
  gint ythickness;
  gint length, ideal_length;
  gdouble lower, upper;		/* Upper and lower limits, in ruler units */
  gdouble increment;		/* Number of pixels per unit */
  gint scale;			/* Number of units per major unit */
  gdouble subd_incr;
  gdouble start, end, cur;
  gchar unit_str[32];
  gint digit_height;
  gint digit_offset;
  gint text_width;
  gint pos;
  PangoLayout *layout;
  PangoRectangle logical_rect, ink_rect;

  if (!GTK_WIDGET_DRAWABLE (ruler)) 
    return;

  widget = GTK_WIDGET (ruler);

  xthickness = widget->style->xthickness;
  ythickness = widget->style->ythickness;

  layout = gtk_widget_create_pango_layout (widget, "012456789");
  pango_layout_get_extents (layout, &ink_rect, &logical_rect);
  
  digit_height = PANGO_PIXELS (ink_rect.height) + 2;
  digit_offset = ink_rect.y;

  width = widget->allocation.width;
  height = widget->allocation.height - ythickness * 2;
   
  gtk_paint_box (widget->style, ruler->backing_store,
		 GTK_STATE_NORMAL, GTK_SHADOW_OUT, 
		 NULL, widget, "hruler",
		 0, 0, 
		 widget->allocation.width, widget->allocation.height);

  cr = gdk_cairo_create (ruler->backing_store);
  gdk_cairo_set_source_color (cr, &widget->style->fg[widget->state]);
 
  cairo_rectangle (cr, 
		   xthickness,
		   height + ythickness,
		   widget->allocation.width - 2 * xthickness,
		   1);

  upper = ruler->upper / ruler->metric->pixels_per_unit;
  lower = ruler->lower / ruler->metric->pixels_per_unit;

  if ((upper - lower) == 0) 
    goto out;

  increment = (gdouble) width / (upper - lower);

  /* determine the scale
   *  We calculate the text size as for the vruler instead of using
   *  text_width = gdk_string_width(font, unit_str), so that the result
   *  for the scale looks consistent with an accompanying vruler
   */
  scale = ceil (ruler->max_size / ruler->metric->pixels_per_unit);
  g_snprintf (unit_str, sizeof (unit_str), "%d", scale);
  text_width = strlen (unit_str) * digit_height + 1;

  for (scale = 0; scale < MAXIMUM_SCALES; scale++)
    if (ruler->metric->fpcruler_scale[scale] * fabs(increment) > 2 * text_width)
      break;

  if (scale == MAXIMUM_SCALES)
    scale = MAXIMUM_SCALES - 1;

  /* drawing starts here */
  length = 0;
  for (i = MAXIMUM_SUBDIVIDE - 1; i >= 0; i--)
    {
      subd_incr = (gdouble) ruler->metric->fpcruler_scale[scale] / 
	          (gdouble) ruler->metric->subdivide[i];
      if (subd_incr * fabs(increment) <= MINIMUM_INCR) 
	continue;

      /* Calculate the length of the tickmarks. Make sure that
       * this length increases for each set of ticks
       */
      ideal_length = height / (i + 1) - 1;
      if (ideal_length > ++length)
	length = ideal_length;

      if (lower < upper)
	{
	  start = floor (lower / subd_incr) * subd_incr;
	  end   = ceil  (upper / subd_incr) * subd_incr;
	}
      else
	{
	  start = floor (upper / subd_incr) * subd_incr;
	  end   = ceil  (lower / subd_incr) * subd_incr;
	}

      for (cur = start; cur <= end; cur += subd_incr)
	{
	  pos = ROUND ((cur - lower) * increment);

	  cairo_rectangle (cr, 
			   pos, height + ythickness - length, 
			   1,   length);

	  /* draw label */
	  if (i == 0)
	    {
	      g_snprintf (unit_str, sizeof (unit_str), "%d", (int) cur);
	      
	      pango_layout_set_text (layout, unit_str, -1);
	      pango_layout_get_extents (layout, &logical_rect, NULL);

              gtk_paint_layout (widget->style,
                                ruler->backing_store,
                                GTK_WIDGET_STATE (widget),
				FALSE,
                                NULL,
                                widget,
                                "hruler",
                                pos + 2, ythickness + PANGO_PIXELS (logical_rect.y - digit_offset),
                                layout);
	    }
	}
    }

  cairo_fill (cr);
out:
  cairo_destroy (cr);

  g_object_unref (layout);
}


static void
gtk_hfpcruler_draw_pos (GtkFpcRuler *fpcruler)
{
    GtkWidget *widget;
    int i;
    gint x, y;
    gint width, height;
    gint bs_width, bs_height;
    gint xthickness;
    gint ythickness;
    gfloat increment;
    GdkGCValues values;
    GdkColor color;

    if (fpcruler->backing_store == NULL) return;

    g_return_if_fail (fpcruler != NULL);
    g_return_if_fail (GTK_IS_HFPC_RULER (fpcruler));

    if (GTK_WIDGET_DRAWABLE (fpcruler))
    {
        widget = GTK_WIDGET (fpcruler);

        if(fpcruler->xor_gc==NULL)
        {
	        values.function = GDK_INVERT;
	        values.subwindow_mode = GDK_INCLUDE_INFERIORS;
	        fpcruler->xor_gc = gdk_gc_new_with_values (widget->window,
						   &values,
						   GDK_GC_FUNCTION |
						   GDK_GC_SUBWINDOW);
        }

        if(fpcruler->active_pos_gc==NULL)
        {
	        fpcruler->active_pos_gc = gdk_gc_new(widget->window);
	        gdk_color_parse("cyan", &color);

            gdk_gc_set_rgb_fg_color(fpcruler->active_pos_gc,&color);
        }
        if(fpcruler->passive_pos_gc==NULL)
        {
	        fpcruler->passive_pos_gc = gdk_gc_new(widget->window);
        }

        if(fpcruler->selected_pos==1) bar_active=0;
        else if(fpcruler->selected_pos==2) bar_active=1;


        xthickness = widget->style->xthickness;
        ythickness = widget->style->ythickness;
        width = widget->allocation.width;
        height = widget->allocation.height - ythickness * 2;

        bs_width = height / 2;
        bs_width |= 1;  /* make sure it's odd */
        bs_height = bs_width / 2 + 1;

        if ((bs_width > 0) && (bs_height > 0))
	    {
	        /*  if a backing store exists, restore the fpcruler  */
	        if (fpcruler->backing_store && fpcruler->non_gr_exp_gc)
	        gdk_draw_pixmap (fpcruler->widget.window,
			     fpcruler->non_gr_exp_gc,
			     fpcruler->backing_store,
			     fpcruler->xsrc1, fpcruler->ysrc1,
			     fpcruler->xsrc1, fpcruler->ysrc1,
			     bs_width, bs_height);

	        increment = (gfloat) width / (fpcruler->upper - fpcruler->lower);
	        x = ROUND ((fpcruler->position1 - fpcruler->lower) * increment) + 
              (xthickness - bs_width) / 2 - 1;
	        y = (height + bs_height) / 2 + ythickness;

            if(bar_active==0)
            {
	            for (i = 0; i < bs_height; i++)
	                gdk_draw_line (widget->window, fpcruler->active_pos_gc,
			            x + (bs_height - 1 - i), y + i,
			            x + bs_width - 1 - (bs_height - 1 - i), y + i);
            }
            else
            {
	            for (i = 0; i < bs_height; i++)
	                gdk_draw_line (widget->window, fpcruler->passive_pos_gc,
			            x + (bs_height - 1 - i), y + i,
			            x + bs_width - 1 - (bs_height - 1 - i), y + i);
            }

            if (fpcruler->selected_pos == 1)
            { 
                if (x != fpcruler->xsrc1 || pos1_first)
                {                
                    if (!pos1_first)
                    {
                        // if they just clicked, we should not erase the last location
                        gdk_gc_set_function(fpcruler->xor_gc, GDK_INVERT);
                        gdk_draw_line (widget->parent->window, fpcruler->xor_gc,
			                    fpcruler->xsrc1 + SCROLLBAR_WIDTH + WINDOW_BORDER, UPPER_BORDER, 
			                    fpcruler->xsrc1 + SCROLLBAR_WIDTH + WINDOW_BORDER, 
			                    widget->parent->parent->allocation.height - LOWER_BORDER);
                    }

	                fpcruler->xsrc1 = x;
	                fpcruler->ysrc1 = y;
                    gdk_gc_set_function(fpcruler->xor_gc, GDK_INVERT);
                    gdk_draw_line (widget->parent->window, fpcruler->xor_gc,
			                fpcruler->xsrc1 + SCROLLBAR_WIDTH + WINDOW_BORDER, UPPER_BORDER, 
			                fpcruler->xsrc1 + SCROLLBAR_WIDTH + WINDOW_BORDER, 
			                widget->parent->parent->allocation.height - LOWER_BORDER);

                }

                pos1_first = 0;
            }

            /* second position */

	        if (fpcruler->backing_store && fpcruler->non_gr_exp_gc)
	            gdk_draw_pixmap (fpcruler->widget.window,
			        fpcruler->non_gr_exp_gc,
			        fpcruler->backing_store,
			        fpcruler->xsrc2, fpcruler->ysrc2,
			        fpcruler->xsrc2, fpcruler->ysrc2,
			        bs_width, bs_height);

	         increment = (gfloat) width / (fpcruler->upper - fpcruler->lower);

	        x = ROUND ((fpcruler->position2 - fpcruler->lower) * increment) + (xthickness - bs_width) / 2 - 1;
	        y = (height + bs_height) / 2 + ythickness;

            if(bar_active==1)
            {
	            for (i = 0; i < bs_height; i++)
	                gdk_draw_line (widget->window, fpcruler->active_pos_gc,
			                x + (bs_height - 1 - i), y + i,
			                x + bs_width - 1 - (bs_height - 1 - i), y + i);
            }
            else
            {
	            for (i = 0; i < bs_height; i++)
	                gdk_draw_line (widget->window, fpcruler->passive_pos_gc,
			             x + (bs_height - 1 - i), y + i,
			             x + bs_width - 1 - (bs_height - 1 - i), y + i);
            }

            if (fpcruler->selected_pos == 2)
            {
                if (x != fpcruler->xsrc2 || pos2_first)
                {
                    if (!pos2_first)
                    {
                        gdk_gc_set_function(fpcruler->xor_gc, GDK_INVERT);
	                    gdk_draw_line (widget->parent->window, fpcruler->xor_gc,
			                fpcruler->xsrc2 + SCROLLBAR_WIDTH + WINDOW_BORDER, UPPER_BORDER, 
			                fpcruler->xsrc2 + SCROLLBAR_WIDTH + WINDOW_BORDER, 
			                widget->parent->parent->allocation.height - LOWER_BORDER);
                    }

	                fpcruler->xsrc2 = x;
	                fpcruler->ysrc2 = y;
                    gdk_gc_set_function(fpcruler->xor_gc, GDK_INVERT);
	                gdk_draw_line (widget->parent->window, fpcruler->xor_gc,
			            fpcruler->xsrc2 + SCROLLBAR_WIDTH + WINDOW_BORDER, UPPER_BORDER, 
			            fpcruler->xsrc2 + SCROLLBAR_WIDTH + WINDOW_BORDER, 
			            widget->parent->parent->allocation.height - LOWER_BORDER);


	            }
                pos2_first = 0;
            }
        }
    }
}

static void
gtk_hfpcruler_erase_pos (GtkFpcRuler *fpcruler)
{
    GtkWidget *widget;
    int i;
    gint x, y;
    gint width, height;
    gint bs_width, bs_height;
    gint xthickness;
    gint ythickness;
    gfloat increment;
    GdkGCValues values;
    GdkColor color;

    if (fpcruler->backing_store == NULL) return;

    g_return_if_fail (fpcruler != NULL);
    g_return_if_fail (GTK_IS_HFPC_RULER (fpcruler));

    if (GTK_WIDGET_DRAWABLE (fpcruler))
    {
        widget = GTK_WIDGET (fpcruler);

      if(fpcruler->xor_gc==NULL)
    {
	values.function = GDK_INVERT;
	values.subwindow_mode = GDK_INCLUDE_INFERIORS;
	fpcruler->xor_gc = gdk_gc_new_with_values (widget->window,
						   &values,
						   GDK_GC_FUNCTION |
						   GDK_GC_SUBWINDOW);
      }

      if(fpcruler->active_pos_gc==NULL){
	fpcruler->active_pos_gc = gdk_gc_new(widget->window);
	gdk_color_parse("cyan", &color);

    gdk_gc_set_rgb_fg_color(fpcruler->active_pos_gc,&color);
      }
      if(fpcruler->passive_pos_gc==NULL){
	fpcruler->passive_pos_gc = gdk_gc_new(widget->window);
      }

        if(fpcruler->selected_pos==1) bar_active=0;
        else if(fpcruler->selected_pos==2) bar_active=1;


        xthickness = widget->style->xthickness;
        ythickness = widget->style->ythickness;
        width = widget->allocation.width;
        height = widget->allocation.height - ythickness * 2;

        bs_width = height / 2;
        bs_width |= 1;  /* make sure it's odd */
        bs_height = bs_width / 2 + 1;

        if ((bs_width > 0) && (bs_height > 0))
	    {
	        /*  if a backing store exists, restore the fpcruler  */
	        if (fpcruler->backing_store && fpcruler->non_gr_exp_gc)
	        gdk_draw_pixmap (fpcruler->widget.window,
			     fpcruler->non_gr_exp_gc,
			     fpcruler->backing_store,
			     fpcruler->xsrc1, fpcruler->ysrc1,
			     fpcruler->xsrc1, fpcruler->ysrc1,
			     bs_width, bs_height);

	        increment = (gfloat) width / (fpcruler->upper - fpcruler->lower);

	        x = ROUND ((fpcruler->position1 - fpcruler->lower) * increment) + 
              (xthickness - bs_width) / 2 - 1;
	        y = (height + bs_height) / 2 + ythickness;

            if(bar_active==0)
            {
	            for (i = 0; i < bs_height; i++)
	                gdk_draw_line (widget->window, fpcruler->active_pos_gc,
			            x + (bs_height - 1 - i), y + i,
			            x + bs_width - 1 - (bs_height - 1 - i), y + i);
            }
            else
            {
	            for (i = 0; i < bs_height; i++)
	                gdk_draw_line (widget->window, fpcruler->passive_pos_gc,
			            x + (bs_height - 1 - i), y + i,
			            x + bs_width - 1 - (bs_height - 1 - i), y + i);
            }
          
            if (fpcruler->selected_pos == 1)
            {
                gdk_gc_set_function(fpcruler->xor_gc, GDK_INVERT);
                gdk_draw_line (widget->parent->window, fpcruler->xor_gc,
			        fpcruler->xsrc1 + SCROLLBAR_WIDTH + WINDOW_BORDER, UPPER_BORDER, 
			        fpcruler->xsrc1 + SCROLLBAR_WIDTH + WINDOW_BORDER, 
			        widget->parent->parent->allocation.height - LOWER_BORDER);
            }

            /* second position */

	        if (fpcruler->backing_store && fpcruler->non_gr_exp_gc)
	            gdk_draw_pixmap (fpcruler->widget.window,
			        fpcruler->non_gr_exp_gc,
			        fpcruler->backing_store,
			        fpcruler->xsrc2, fpcruler->ysrc2,
			        fpcruler->xsrc2, fpcruler->ysrc2,
			        bs_width, bs_height);

	         increment = (gfloat) width / (fpcruler->upper - fpcruler->lower);

	        x = ROUND ((fpcruler->position2 - fpcruler->lower) * increment) + (xthickness - bs_width) / 2 - 1;
	        y = (height + bs_height) / 2 + ythickness;


            if(bar_active==1)
            {
	            for (i = 0; i < bs_height; i++)
	                gdk_draw_line (widget->window, fpcruler->active_pos_gc,
			                x + (bs_height - 1 - i), y + i,
			                x + bs_width - 1 - (bs_height - 1 - i), y + i);
            }
            else
            {
	            for (i = 0; i < bs_height; i++)
	                gdk_draw_line (widget->window, fpcruler->passive_pos_gc,
			             x + (bs_height - 1 - i), y + i,
			             x + bs_width - 1 - (bs_height - 1 - i), y + i);
            }

            if (fpcruler->selected_pos == 2)
            {
                gdk_gc_set_function(fpcruler->xor_gc, GDK_INVERT);
	            gdk_draw_line (widget->parent->window, fpcruler->xor_gc,
			        fpcruler->xsrc2 + SCROLLBAR_WIDTH + WINDOW_BORDER, UPPER_BORDER, 
			        fpcruler->xsrc2 + SCROLLBAR_WIDTH + WINDOW_BORDER, 
			        widget->parent->parent->allocation.height - LOWER_BORDER);
            }
                
        }
    }
}

